//
//  ViewController.swift
//  studyRxSwiftDemo
//
//  Created by jemi on 2019/12/16.
//  Copyright © 2019 jemi. All rights reserved.
//

import UIKit
import RxSwift
import SnapKit
import RxCocoa

class ViewController: UIViewController {
    var textField:UITextField = UITextField()
    var bag:DisposeBag = DisposeBag()
    @objc var person:Person = Person()
    var label:UILabel?
    var button:UIButton?
    var textField1:UITextField = UITextField()
    var label2:UILabel = UILabel()
    var mylistViewModel = MyListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //textfiled文本响应
        setupTextField()
        
        //button点击事件
        setupButton()
        
        //KVO
        setupKVO()
        
        //通知
        setupNotification()
        
        //手势
        setupGestureRecognizer()
        
        //定时器
        setupTimer()
        
        //filter
        setupFilter()
        
        //debug
        setupDebug()
        
        //dirver
        setupDriver()
        
        //combineLatest 监听多个
        setupCombineLatest()
        
        //事件监听
        setupControlEvent()
        
        //双向绑定
        doubleBind()
        
    }

    func setupTextField(){
        textField.text = "1234";
        view.addSubview(textField)
        textField.snp.makeConstraints { (m) in
            m.leading.equalToSuperview().offset(20)
            m.top.equalToSuperview().offset(100)
            m.trailing.equalToSuperview().offset(-20)
            m.height.equalTo(40)
        }
        
        /*
         *  注意throttle 与debounce 的区别
         *  throttle：马上执行一次，之后按指定时间继续执行
         *  debounce：电梯函数，倒计时结束前收到信号重置倒计时，倒计时结束后才执行1次
         */
        let obserText = textField.rx.text.orEmpty.changed
        obserText.debounce(RxTimeInterval.seconds(2), scheduler: MainScheduler.instance).subscribe(onNext: { (text) in
            print(text)
        }).disposed(by: bag)
        
//        obserText.subscribe(onNext: { (text) in
//            print(text)
//        }).disposed(by: bag)
    }
    
    func setupButton(){
        let btn = UIButton()
        btn.setTitle("测试按钮", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.black.cgColor
        btn.layer.cornerRadius = 7
        btn.clipsToBounds = true
        button = btn
        view.addSubview(btn)
        btn.snp.makeConstraints { (m) in
            m.leading.trailing.height.equalTo(textField)
            m.top.equalTo(textField.snp_bottom).offset(40)
        }
        
        btn.rx.tap.subscribe(onNext: { [weak self] in
            print("1")
            self?.person.name = "jiuge"
            self?.navigationController?.pushViewController(MyTableViewVC(), animated: true)
        }).disposed(by: bag)
    }
    
    func setupKVO(){
        //观察的Person类中name属性必须同时用 @objc 和 dynamic 修饰
        person.rx.observeWeakly(String.self, "name").subscribe(onNext: { (name) in
            print("name = " + name!)
        }).disposed(by: bag)
        
    }
    
    func setupNotification(){
    NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification).subscribe{even in
            print(even)
        }.disposed(by: bag)
    }
    
    func setupGestureRecognizer() {
        let label = UILabel()
        label.text = "测试手势"
        self.label = label
        label.backgroundColor = .red
        label.font = UIFont.systemFont(ofSize: 15)
        view.addSubview(label)
        label.snp.makeConstraints { (m) in
            m.leading.equalTo(textField)
            m.top.equalTo(textField.snp_bottom).offset(100)
            m.height.equalTo(25)
        }
        
        let tap = UITapGestureRecognizer()
        label.addGestureRecognizer(tap)
        label.isUserInteractionEnabled = true
        tap.rx.event.subscribe { (even) in
            print("手势点击")
        }.disposed(by: bag)
    }
    
    func setupTimer(){
        let timer = Observable<Int>.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance)
        timer.subscribe(onNext: { (time) in
            print(time)
        }).disposed(by: bag)
    }
    
    func setupFilter() {
        Observable.of(2,0,8,99,47,37,5,44,2,34,22,12).filter { (num) -> Bool in
            num > 10
        }.subscribe(onNext: { (num) in
            print(num)
        }).disposed(by: bag)
        
        //过滤连续重复
        Observable.of(2,33,4,3,3,5,11,11,2).distinctUntilChanged().subscribe(onNext: { (num) in
            print("num == \(num)")
        }).disposed(by: bag)
        
        //take:处理前n个
        Observable.of(2,3,4,5).take(2).subscribe(onNext: { (num) in
            print("take == \(num)")
        }).disposed(by: bag)
        
        //takeLast:处理后N个
        Observable.of(7,8,9,12).takeLast(1).subscribe(onNext: { (num) in
            print("takeLast == \(num)")
        }).disposed(by: bag)
    }
    
    func setupDebug(){
        Observable.of("2","3").startWith("1").debug("调试1").subscribe(onNext: { (result) in
            print(result)
            
        }).disposed(by: bag)
    }
    
    func setupDriver(){
        textField.rx.text.orEmpty.asDriver().drive((label?.rx.text)!).disposed(by: bag)
        
        //根据内容字数决定按钮是否可用
        textField.rx.text.orEmpty.asDriver().map{ $0.count > 5 }
        .drive((button?.rx.isEnabled)!)
        .disposed(by: bag)
    }
    
    func setupCombineLatest(){
        view.addSubview(textField1)
        textField1.placeholder = "请输入"
        textField1.snp.makeConstraints { (m) in
            m.leading.equalTo(label!)
            m.top.equalTo(label!.snp_bottom).offset(30)
            m.trailing.height.equalTo(textField)
        }
        
        view.addSubview(label2)
        label2.snp.makeConstraints { (m) in
            m.leading.trailing.equalTo(textField1)
            m.top.equalTo(textField1.snp_bottom).offset(30)
            m.height.equalTo(40)
        }
        
        Observable.combineLatest(textField.rx.text.orEmpty,textField1.rx.text.orEmpty){ textvalue1, textvalue2 -> String in
            return "您输入的是：" + textvalue1 + textvalue2
            }.asDriver(onErrorJustReturn: "sss").drive(label2.rx.text).disposed(by: bag)
            
    }
    
    func setupControlEvent(){
        textField1.rx.controlEvent(.editingChanged).subscribe(onNext: { (changeText) in
            print("changeText = = \(changeText)" )
            }).disposed(by: bag)
    }
    
    func doubleBind(){
        mylistViewModel.username.asObservable().bind(to: textField1.rx.text).disposed(by: bag)
        textField1.rx.text.orEmpty.bind(to: mylistViewModel.username).disposed(by: bag)
        
        mylistViewModel.userinfo.bind(to: label2.rx.text).disposed(by: bag)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        UIApplication.shared.keyWindow?.endEditing(true)
    }
}



